import {Component, OnInit} from '@angular/core';
import {Globals} from '../../../globals';
import {TreeNodeInterface} from '../../../shared/interface/TreeNodeInterface';
import {BaseService} from '../../../shared/service/base.service';
import {ApiUrl} from '../../../config/api-url';
import {PageHelper} from '../../../utils/page-helper-model';
import {ActivatedRoute} from '@angular/router';
import {Consts} from '../../../config/consts';
import {RoleIdEnum} from '../../../enums/role-id.enum';

@Component({
  selector: 'app-agency-list',
  templateUrl: './agency-list.component.html',
  styleUrls: ['./agency-list.component.less']
})
export class AgencyListComponent implements OnInit {

  isMobile = Globals.isMobile();
  listOfMapData = [];
  mapOfExpandedData: { [key: string]: TreeNodeInterface[] } = {};
  isSpinning = false;

  // 显示编辑机构模态框
  isVisible = false;
  // 分页
  pageHelper: PageHelper = new PageHelper;


  // 显示二维码模态框
  qrCodeVisible = false;
  // 二维码内容
  qrCodeContent: any;
  // 下载二维码的文件名称
  fileName: any;
  agencyId: any;
  userInfo: any;
  roleIdEnum = {
    SUPER_ADMINISTRATOR: RoleIdEnum.SUPER_ADMINISTRATOR,
    AGENT: RoleIdEnum.AGENT,
  };
  isVisibleConfiguration: boolean;
  item: any;
  // 控制输入费率显示隐藏
  agencyInfoDetailVisible = false;

  constructor(private baseService: BaseService, private activatedRoute: ActivatedRoute) {
    // this.listOfMapData = AGENTS;
    this.activatedRoute.queryParams.subscribe(params => {
      if (params['agencyNo'] != null) {
        this.pageHelper.keyword = params['agencyNo'];
        this.findList();
      }
    });
  }

  ngOnInit(): void {
    this.userInfo = JSON.parse(sessionStorage.getItem(Consts.USER_INFO));
    this.findList();
  }


  // 获取列表
  findList() {
    this.isSpinning = true;
    this.baseService.findListByKeyword(ApiUrl.AgencyUrl + '/list', this.pageHelper).subscribe(
      data => {
        this.isSpinning = false;
        if (data.status == 0) {
          this.listOfMapData = data.data;
          if (this.listOfMapData.length > 0) {
            this.listOfMapData.forEach(item => {
              this.mapOfExpandedData[item.key] = this.baseService.zorro.convertTreeToList(item);
            });
          }
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );
  }

  findListByKeyword() {
    this.findList();
  }

  addAgency() {
    this.isVisible = true;
  }


  // 子组件向父组件传值
  setVisible(body) {
    this.isVisible = body.isVisible;
    this.findList();
    this.agencyId = 0;
  }

  setAgencyInfoDetailVisible(body){
    this.agencyInfoDetailVisible = body.agencyInfoDetailVisible;
  }

  loadData() {
    this.findList();
  }

  // 显示二维码模态框
  showQrCode(agency: any) {
    this.baseService.get(ApiUrl.Config + '/findBackEndUrl?type=wap').subscribe(
      data => {
        if (data.status == 0) {
          if (data.data == null || data.data.url == null) {
            this.baseService.layer.messageError('找不到地址');
            return;
          }
          this.qrCodeVisible = true;
          this.qrCodeContent = data.data.url + '/#/pages/register/register?agencyId=1';
          this.fileName = agency.agencyNo + '-' + agency.alias;
        } else {
          this.baseService.layer.messageError(data.msg);
        }
      }
    );

  }

  setQrCodeVisible($event: any) {
    this.qrCodeVisible = $event;
  }

  editAgency(item: any) {
    this.isVisible = true;
    this.agencyInfoDetailVisible = true;
    this.agencyId = item.id;
  }

  configuration(item: any) {
    this.item = item;
    this.isVisibleConfiguration = true;
  }

  setConfiguration(event) {
    this.isVisibleConfiguration = event;
    this.findList();
  }

  // 更改对接模式
  updateDockingStatus(item) {
    let status = 0;
    let msg = null;
    if (item.dockingStatus == 1) {
      status = 0;
      msg = '确定要关闭[' + item.agencyNo + ']该机构的对接权限？';
    } else {
      status = 1;
      msg = '确定要开启[' + item.agencyNo + ']该机构的对接权限？';
    }

    this.baseService.layer.modalConfirm(msg, result => {
      if (result) {
        let body = {
          id: item.id,
          dockingStatus: status
        };
        this.baseService.put(ApiUrl.AgencyUrl + '/updateDockingStatus', body).subscribe(
          data => {
            if (data.status == 0) {
              if (status == 1) {
                this.baseService.layer.messageSuccess('该机构的对接权限开启成功！');
              } else {
                this.baseService.layer.messageSuccess('该机构的对接权限关闭成功！');
              }
              this.findList();
            } else {
              this.baseService.layer.messageError('修改失败：' + data.msg);
            }
          }
        );
      }
    });
  }

  changeAgencyStatus(param, status) {

    param.status = status;

    let msg = null;
    if (param.status == 1) {
      msg = '确定要恢复[' + param.agencyNo + ']该机构吗？';
    } else {
      msg = '确定要冻结[' + param.agencyNo + ']该机构吗？';
    }

    this.baseService.layer.modalConfirm(msg, result => {
      if (result) {
        this.baseService.post(ApiUrl.AgencyUrl + '/changeAgencyStatus', param).subscribe(
          data => {
            if (data.status == 0) {
              if (param.status == 1) {
                this.baseService.layer.messageSuccess('恢复机构成功！');
              } else {
                this.baseService.layer.messageSuccess('冻结机构成功！');
              }
              this.findList();
            } else {
              this.baseService.layer.messageError('修改失败：' + data.msg);
            }
          }
        );
      }
    });
  }

  resetPassword(data) {
    let param = {
      id: data.userId
    };
    this.baseService.layer.modalConfirm('确定要重置密码吗？', result => {
      if (result) {
        this.baseService.put(ApiUrl.UserUrl + '/resetPwdById', param).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('重置密码成功！');
              this.findList();
            } else {
              this.baseService.layer.messageError('重置密码失败：' + data.msg);
            }
          }
        );
      }
    });
  }
  resetOperatePassword(data) {
    let param = {
      id: data.userId
    };
    this.baseService.layer.modalConfirm('确定要重置操作密码吗？', result => {
      if (result) {
        this.baseService.put(ApiUrl.UserUrl + '/resetOperatePwdById', param).subscribe(
          data => {
            if (data.status == 0) {
              this.baseService.layer.messageSuccess('重置操作密码成功！新密码为'+ data.data);
              this.findList();
            } else {
              this.baseService.layer.messageError('重置操作密码失败：' + data.msg);
            }
          }
        );
      }
    });
  }
}
